﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using MyTestRunner.Domain;
using System.IO;

namespace MyTestRunner
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                string assemblyFile = args[0];
                RunTests(assemblyFile);
            }
            else
            {
                PrintUsage();
            }

            Console.WriteLine("{0}Done. Press any key to terminate...", Environment.NewLine);
            Console.ReadKey();
        }

        private static void RunTests(string assemblyFile)
        {
            assemblyFile = Path.GetFullPath(assemblyFile);
            Assembly assemblyWithTests = /*Assembly.LoadFile(assemblyFile);*/Assembly.LoadFrom(assemblyFile);

            ITestFinder testFinder = new MsTestFinder();

            foreach (MethodInfo testMethod in testFinder.FindTestMethods(assemblyWithTests))
            {
                MethodInfo setUpMethod;
                if (!testFinder.TryGetSetUpMethod(testMethod.DeclaringType, out setUpMethod))
                {
                    setUpMethod = null;
                }

                MethodInfo tearDownMethod;
                if (!testFinder.TryGetTearDownMethod(testMethod.DeclaringType, out tearDownMethod))
                {
                    tearDownMethod = null;
                }

                Type expectedException;
                if (!testFinder.TryGetExpectedExceptionType(testMethod, out expectedException))
                {
                    expectedException = null;
                }

                TestRunResult result = new TestRunner().Run(testMethod, expectedException, setUpMethod, tearDownMethod);
                if (!result.IsSuccess)
                {
                    DisplayFailture(result);
                }
            }
        }

        private static void DisplayFailture(TestRunResult result)
        {
            ConsoleColor original = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("{0}.{1}: ", result.Method.DeclaringType.FullName, result.Method.Name);
            Console.ForegroundColor = original;
            Console.WriteLine("{0}", result.UnexpectedException.Message);
            Console.WriteLine();
        }

        private static void PrintUsage()
        {
            Console.WriteLine("MyTestRunner.exe [location of test assembly]");
            Console.WriteLine(@"Eg: MyTestRunner.exe c:\test.dll");
        }
    }
}
